'use strict';

const jwt = require('jwt-simple')
const Service = require('egg').Service
const token_expire = 60 * 60 * 24 * 7

class TokenService extends Service {

  /**
   * 生成token
   * @param {User} user 用户数据
   */
   async generate(user) {
    //console.log(user)
    let token = jwt.encode(
      {
        _id: user._id,
        iat: +new Date(),
        exp: +new Date() + 7 * 24 * 60 * 60 * 1000
      },
      this.ctx.app.config.secret
    )

    this.app.redis.set(token, String(user._id))
    this.app.redis.expire(token, token_expire)
    return token
  }

  async newGenerate(verification){  
    let token = jwt.encode(  //身份信息与密钥使用jwt编译,生成au
      {
        auth: verification,
      },
      this.ctx.app.config.secret
    )
    return token
  }
}

module.exports = TokenService;
